
print("修饰器")
def xiushiqi(func):
    def wrapper(*args,**kwargs):
        print("方法执行前操作")
        res= func(*args,**kwargs)
        print("方法执行后操作")
        return res
    return wrapper

@xiushiqi
def add(a,b):
    # print(a+b)
    return a+b
print(add(1,2))


print("单例模式")
import threading as td
class SingleTon:
    INSTANCE=None
    lock=td.Lock()
    def __new__(cls, *args, **kwargs):
        if cls.INSTANCE is None:
            with cls.lock:
                if cls.INSTANCE is None:
                    cls.INSTANCE=super().__new__(cls)

instance_1=SingleTon()
intanse_2=SingleTon()
print(instance_1==intanse_2)

print("判断字符串是否存在于字符串中")
print("python" in "python is best language")
print("查找字符串，返回第一个出现的下标find  index  rfind")
sentence="Python is awesome.123123123Python is dynamic."
first_occurrence = sentence.find("Python")
first_occurrence_02 = sentence.index("Python")
last_occurrence = sentence.rfind("Python")
# 列表没有find方法
# print([1,2,3].find(1))
print(first_occurrence,first_occurrence_02,last_occurrence)
print("capitalize() 方法将字符串的首字母大写，title() 方法将字符串每个单词的首字母大写")
text="hello world"
print(text.capitalize())
print(text.title())

# 计算非重复元素个数：不使用封装好的方法
def caculate_longest_substring_length(str):
    num=len(str)
    if num==0:
        return 0
    char_index={}
    left=0
    max_length=0
    for right in range(num):
        # if str[right] in char_index and char_index[str[right]]>=left:
        if str[right] in char_index:
            left=char_index[str[right]]+1
        char_index[str[right]]=right
        max_length=max(max_length,right-left+1)
    return max_length
print(caculate_longest_substring_length("abcbcbb"))
print(caculate_longest_substring_length("abcabcdbb"))
print(caculate_longest_substring_length("aa"))
print(caculate_longest_substring_length("abc"))
print("使用封装好的方法求非重复元素个数")
print(set(list("abcabcbb")))
print(set(list("abcabcdbb")))
print(set(list("aa")))
print(set(list("abc")))

print("处理CSV文件")
import csv
with open("files/csv001.csv", "r", encoding="utf-8") as file:
    # 此时读取的数据是包含表头的
    # reader=csv.reader(file)
    # reader是一个迭代器对象
    # print(type(reader))
    # for row in reader:
    #     print(row)

    reader=csv.reader(file)
    # reader是一个迭代器对象，使用next()方法后，reader就指向了表头的下一行
    header=next(reader)
    print("循环中将表头已经过滤掉")
    for row in reader:
        print(row)
        # 将每一行数据都和表头结合形成字典
        row[2]=int(row[2])
        row[4]=float(row[4])
        print(dict(zip(header,row)))

    # 将 <class '_csv.reader'> 迭代器对象转化为列表
    # reader = csv.reader(file)
    # data_list=list(reader)
    # print(data_list)
    # for row in data_list:
    #     print(row)


print("写入CSV文件")
data=[["name","age"],["alice",30],["bob",25]]
# 参数w表示覆盖写  参数a表示增加写
with open("files/csv002.csv", "w", newline="") as file:
    writer=csv.writer(file)
    # writerows表示批量写入二维数组
    writer.writerows(data)

data2=["jim",23]
with open("files/csv003.csv", "a", newline="") as file:
    writer=csv.writer(file)
    # writerow表示写入一维数组
    # writer.writerow(data2)

with open("files/csv003.csv", "r") as file:
    reader=csv.reader(file)
    for row in reader:
        print(row)

print("读取CSV文件直接取值为字典")
with open("./files/csv001.csv",mode="r",encoding="utf-8") as file:
    reader=csv.DictReader(file)
    for row in reader:
        print(row)
        print(type(row))
print("字典的列表数据写入CSV文件")
import csv
data = [
    {'name': 'Alice', 'age': 30, 'city': 'New York'},
    {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
    {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
]
with open(file="./files/csv004.csv",mode="w",encoding="utf-8",newline="") as file:
    # 注意位置参数是f,而不是file
    writer=csv.DictWriter(f=file,fieldnames=["name","age","city"])
    writer.writeheader()
    for d in data:
        writer.writerow(d)

import json
print("处理JSON文件")
data=None
with open("files/json001.json", "r", encoding="utf-8") as file:
    data = json.load(file)
    print(data)
    print(type(data))
    print(type(data["score"]))
    print(type(data["food"]))

with open("files/json002.json", "w", encoding="utf-8") as file:
    json.dump(data,file,ensure_ascii=False)

with open("./files/txt001.txt",mode="a",encoding="utf-8") as file:
    for s in "hello world".split():
        file.write(s+"\n")


print("abc"[::-1])
print("aba"[::-1]=="aba")
s=["a","b","a"]
print(s==s[::-1])

list_1=[1,2,3]
print(list_1.pop(1))
print(list_1)
from collections import Counter

list_2 = [1, 2, 3, 2, 1, 2]

# 使用 Counter 计算每个元素的出现次数
counter = Counter(list_2)

# 找到出现次数最多的元素及其次数
most_common_element, most_common_count = counter.most_common(1)[0]
print(f"出现次数最多的元素是: {most_common_element}，出现了 {most_common_count} 次")
print(counter.most_common(n=2))
print(counter.most_common())

print("abac".count("a"))
import collections
sourcer_list=[2,2,3]
tem=collections.Counter(sourcer_list).most_common()
print(tem)
print(tem[-1][0])

print(isinstance("str",str))
print("".join([str(s) for s in sourcer_list]))


source_list_3 = [1221, 21, 23, 22, 43, 6, 3, 5, 7677, 23,21,3]
target_list_3=list(filter(lambda x:x>10,source_list_3))
print(target_list_3)

print(max(source_list_3,key=source_list_3.count))

